import json
import re

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.utils.decorators import method_decorator
from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU
from user.models import User, Area, Address
from django.core.mail import send_mail
from django.conf import settings

from utils.myemail import generate_verify_email_url, decode_email_token
from django.core.cache import cache


class RegisterView(View):
    def get(self, request):
        return render(request, 'register_vue.html')

    # 实现后台检验表单数据的功能
    def post(self, request):
        # 1.获取数据
        data = request.POST
        user_name = data.get('user_name')
        pwd = data.get('pwd')
        cpwd = data.get('cpwd')
        phone = data.get('phone')
        msg_code = data.get('msg_code')
        allow = data.get('allow')
        # 2.校验数据
        if not all([user_name, pwd, cpwd, phone, msg_code]):
            return HttpResponseForbidden('参数不全')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', user_name):
            return HttpResponseForbidden('用户名格式不正确')
        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$', pwd):
            return HttpResponseForbidden('密码格式不正确')
        if pwd != cpwd:
            return HttpResponseForbidden('两次密码不一致')
        if not re.match(r'^1[13456789]\d{9}$', phone):
            return HttpResponseForbidden('手机号码格式不正确')
        if allow != 'on':
            return HttpResponseForbidden('请勾选用户协议')
        # 获取redis短信验证码
        redis_conn = get_redis_connection('verify_code')
        redis_sms_code = redis_conn.get(phone)
        if redis_sms_code:
            redis_sms_code = redis_sms_code.decode()
        if msg_code != redis_sms_code:
            return HttpResponseForbidden('短信验证码有误')
        # checkbox勾选时得到的值时on,而不是True
        if allow != 'on':
            return HttpResponseForbidden('请勾选用户协议')

        # 3.处理业务
        try:
            User.objects.create_user(
                username=user_name,
                password=pwd,
                mobile=phone
            )
            print('用户信息存入成功')
        except Exception as e:
            return HttpResponseForbidden('用户创建失败')

        return redirect('/login/')


# 实现检验用户名是否唯一
class CheckUsernameView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        res = {
            'count': count
        }
        return JsonResponse(res)


# 检测手机号码是否唯一
class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        res = {
            'code': 0,
            'errmsg': '请求成功',
            'count': count
        }
        return JsonResponse(res)


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 1.接收数据
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        remembered = request.POST.get('remembered')

        # 2.校验数据
        if not all([username, pwd]):
            return HttpResponseForbidden('参数不全')
        # 3.处理业务
        # try:
        #     user = User.objects.get(username=username)
        # except Exception as e:
        #     print(e)
        #     return HttpResponseForbidden('用户不存在')
        # 验证用户名和密码
        user = authenticate(request, username=username, password=pwd)
        if user:
            login(request, user)
            print(user.username)
        else:
            print('密码错误')
            return HttpResponseForbidden('密码错误')

        next = request.GET.get('next')
        if next == None:
            next = '/'

        response = redirect(next)
        if remembered != 'on':
            # 不保存登录状态,关闭浏览器时session失效
            request.session.set_expiry(0)
            response.set_cookie('username', user.username)
        else:
            # 按照默认配置,保存两周
            request.session.set_expiry(None)
            response.set_cookie('username', user.username, expires=3600 * 24 * 7)

        # 4.返回响应
        return response


class LogoutView(View):
    def get(self, request):
        logout(request)
        response = redirect('/')
        response.delete_cookie('username')
        return response


# 三种验证用户登陆的方法
# class UserInfoView(View):
#     # 装饰器功能:如果不是认证用户无法进入该页面
#     @method_decorator(login_required)
#     def get(self, request):
#         user = request.user
#         # if user.is_authenticated:
#         context = {
#             'mobile': user.mobile,
#             'email': user.email,
#             'email_active': True
#         }
#         return render(request, 'user_center_info.html', context=context)
class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        # 展示用户中心页面
        user = request.user
        # if user.is_authenticated:
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % user.id, 0, -1)
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_data = {
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'image_url': sku.default_image_url.url
            }
            sku_list.append(sku_data)

        context = {
            'username': user.username,
            'mobile': user.mobile,
            'email': user.email,
            'email_active': user.email_active,
            'skus': sku_list
        }
        return render(request, 'user_center_info.html', context=context)


class EmailSendView(LoginRequiredMixin, View):
    def put(self, request):
        # 1.接收数据
        data = json.loads(request.body.decode())
        email = data.get('email')
        # 2.检验数据
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 9999, 'errmsg': '邮箱格式有误'})
        # 3.处理业务
        user = request.user
        user.email = email
        user.save()
        # send_mail(subject='测试邮件', message='这是测试邮件', from_email=settings.EMAIL_FROM, recipient_list=[user.email])
        from main import send_email_code
        verity_email_url = generate_verify_email_url(user.id)
        title = '美多商城验证码'
        send_email_code.delay(title, verity_email_url, settings.EMAIL_FROM, email)
        # 4.返回响应

        res = {
            'code': 0,
            'errmsg': '成功发送邮件'
        }

        return JsonResponse(res)


class CheckEmailView(View):
    def get(self, request):
        token = request.GET.get('token')
        if not token:
            return HttpResponseForbidden('token丢失')
        id = decode_email_token(token)
        if not id:
            return HttpResponseForbidden('无效token')
        try:
            user = User.objects.get(id=id)
        except Exception as e:
            return HttpResponseForbidden('用户不存在')
        user.email_active = True
        user.save()
        login(request, user)
        request.session.set_expiry(None)
        response = redirect('/info/')
        response.set_cookie('username', user.username, expires=3600 * 24 * 14)
        return response


class AddressView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        if user.default_address:
            default_address_id = user.default_address.id
        else:
            default_address_id = ''
        try:
            addresses = Address.objects.filter(user=user, is_deleted=False)
        except Exception as e:
            print(e)
        addr_list = []
        for addr in addresses:
            addr_dict = {
                'id': addr.id,
                'title': addr.title,
                'receiver': addr.receiver,
                'province': addr.province.name,
                'city': addr.city.name,
                'district': addr.district.name,
                'place': addr.place,
                'mobile': addr.mobile,
                'tel': addr.tel,
                'email': addr.email,
            }
            if addr.id == default_address_id:
                addr_list.insert(0,addr_dict)
            else:
                addr_list.append(addr_dict)


        context = {
            "addresses": json.dumps(addr_list),
            "default_address_id": default_address_id
        }

        return render(request, 'user_center_site.html', context=context)


class AreaView(View):
    def get(self, request):
        # 1.返回省份数据
        # 2.返回城市或区县数据
        # 1.接收数据
        area_id = request.GET.get('area_id')

        # 2.检验数据

        # 3.处理业务
        if not area_id:
            province_list = cache.get("province_list")
            if province_list:
                res = {
                    "code": 0,
                    "errmsg": '成功',
                    'province_list': province_list
                }
                return JsonResponse(res)
            else:
                province = Area.objects.filter(parent__isnull=True)
                province_list = []

                for p in province:
                    p_data = {
                        "id": p.id,
                        "name": p.name
                    }
                    province_list.append(p_data)

                # 把省份数据存入缓存
                cache.set("province_list", province_list, 3600 * 24 * 7)

                res = {
                    "code": 0,
                    "errmsg": '成功',
                    'province_list': province_list
                }
                return JsonResponse(res)
        else:
            area = Area.objects.get(id=area_id)
            subs = area.subs.all()
            subs_list = cache.get("subs_list%s" % area_id)
            if subs_list:
                res = {
                    'code': 0,
                    'errmsg': '成功',
                    'sub_data': {
                        "id": area.id,
                        'name': area.name,
                        'subs': subs_list
                    }
                }
                return JsonResponse(res)
            else:
                subs_list = []
                for s in subs:
                    s_data = {
                        'id': s.id,
                        'name': s.name
                    }
                    subs_list.append(s_data)
                # 市区数据存入缓存
                cache.set("subs_list%s" % area_id, subs_list, 3600 * 24 * 7)
                res = {
                    'code': 0,
                    'errmsg': '成功',
                    'sub_data': {
                        "id": area.id,
                        'name': area.name,
                        'subs': subs_list
                    }
                }
                return JsonResponse(res)


class AddressCreateView(LoginRequiredMixin, View):
    def post(self, request):

        # 1.接收数据
        user = request.user
        data = json.loads(request.body.decode())
        title = data.get('title')
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        # 2.检验数据
        if not all([title, receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 4003, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 4007})

        try:
            province = Area.objects.get(id=province_id)
            city = Area.objects.get(id=city_id)
            district = Area.objects.get(id=district_id)
        except Exception as e:
            return JsonResponse({'code': 9999, 'errmsg': '区域数据有误'})

        # 3.处理业务
        # 以user作为外键在数据库中创建新的地址
        new_addr = Address.objects.create(
            user=user,
            title=title,
            receiver=receiver,
            province=province,
            city=city,
            district=district,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email,
        )
        # 返回地址对象,在js文件中获取到后添加到展示的列表中
        address = {
            'id': new_addr.id,
            'title': new_addr.title,
            'receiver': new_addr.receiver,
            'province': new_addr.province.name,
            'province_id': new_addr.province.id,
            'city': new_addr.city.name,
            'city_id': new_addr.city.id,
            'district': new_addr.district.name,
            'district_id': new_addr.district.id,
            'place': new_addr.place,
            'mobile': new_addr.mobile,
            'tel =': new_addr.tel,
            'email': new_addr.email,
        }

        # 4.返回响应
        res = {
            'code': 0,
            'address': address,
            'errmsg': '成功创建新地址'
        }
        return JsonResponse(res)


class AddressesDefault(LoginRequiredMixin, View):
    def put(self, request, address_id):
        # 1.接收数据
        user = request.user

        # 2.检验数据

        # 3.处理业务
        # 在user模型中创建新的字段,将默认地址id赋值过去
        user.default_address_id = address_id
        user.save()
        addr = Address.objects.get(id=address_id)
        default_addr = {
            'id': addr.id,
            'title': addr.title,
            'receiver': addr.receiver,
            'province': addr.province.name,
            'province_id': addr.province.id,
            'city': addr.city.name,
            'city_id': addr.city.id,
            'district': addr.district.name,
            'district_id': addr.district.id,
            'place': addr.place,
            'mobile': addr.mobile,
            'tel =': addr.tel,
            'email': addr.email,
        }
        # 4.返回响应
        res = {
            'code': 0,
            'errmsg': '设置成功',
            'default_addr': default_addr
        }
        return JsonResponse(res)


class AddressUpdateView(LoginRequiredMixin, View):
    def put(self, request, address_id):
        data = json.loads(request.body.decode())
        title = data.get('title')
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        if not all([title, receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 4003, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 4007, 'errmsg': '手机号码错误'})

        try:
            province = Area.objects.get(id=province_id)
            city = Area.objects.get(id=city_id)
            district = Area.objects.get(id=district_id)
        except Exception as e:
            return JsonResponse({'code': 9999, 'errmsg': '区域数据有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 9999, 'errmsg': '固定电话不正确'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 9999, 'errmsg': '邮箱格式不正确'})

        try:
            address = Address.objects.get(id=address_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '地址id错误'})
        address.title = title
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()
        address_data = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'province_id': address.province.id,
            'city': address.city.name,
            'city_id': address.city.id,
            'district': address.district.name,
            'district_id': address.district.id,
            'place': address.place,
            'mobile': address.mobile,
            'tel =': address.tel,
            'email': address.email,
        }
        res = {
            'code': 0,
            'errmsg': '成功',
            'address': address_data
        }
        return JsonResponse(res)

    def delete(self, request, address_id):
        try:
            addr = Address.objects.get(id=address_id)
        except Exception as e:
            return JsonResponse({'code': 9999, 'errmsg': '地址不存在'})
        user = request.user
        if user.default_address_id == int(address_id):
            user.default_address_id = None
            user.save()
        addr.is_deleted = True
        addr.save()
        res = {
            'code': 0,
            'errmsg': '成功'
        }

        return JsonResponse(res)


class AddressTitleView(LoginRequiredMixin, View):
    def put(self, request, address_id):
        data = json.loads(request.body.decode())
        title = data.get('title')
        if not title:
            return JsonResponse({'cede': 9999, 'errmsg': '参数不全'})
        try:
            address = Address.objects.get(id=address_id)
        except Exception as e:
            return JsonResponse({'code': 9999, 'errmsg': '无效地址id'})
        address.title = title
        address.save()

        res = {
            'code': 0,
            'errmsg': '成功'
        }
        return JsonResponse(res)


class PasswordChangeView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'user_center_pass.html')

    def post(self, request):
        # 1.接收数据
        user = request.user
        old_password = request.POST.get('old_pwd')
        new_password = request.POST.get('new_pwd')
        new_password2 = request.POST.get('new_cpwd')
        # 2.检验数据
        if not all([old_password, new_password, new_password2]):
            return HttpResponseForbidden('参数不全')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return HttpResponseForbidden('密码格式不正确')
        if new_password2 != new_password:
            return HttpResponseForbidden('两次密码不一致')
        # 3.处理业务
        if user.check_password(raw_password=old_password):
            user.set_password(raw_password=new_password)
            user.save()
        logout(request)

        # 4.返回响应
        response = redirect('/login/')
        response.delete_cookie('username')
        return response

class FindPasswordView(View):
    def get(self,request):
        return render(request,'find_password.html')